<?php
// header("Cache-Control: no-cache");
// header("Content-Type: text/event-stream");
// header('Connection: keep-alive');
// header('X-Accel-Buffering: no'); // Nginx: unbuffered responses suitable for Comet and HTTP streaming applications

/**
 * 解决 ob_end_flush() flush() sse报错问题
 */
ob_end_clean();
ob_implicit_flush(1);

$counter = rand(1, 10);
while (true) {
    // Every second, send a "ping" event.

    echo "event: ping\n";
    $curDate = date(DATE_ISO8601);
    echo 'data: {"time": "' . $curDate . '"}';
    echo "\n\n";

    // Send a simple message at random intervals.

    $counter--;

    if (!$counter) {
        echo 'data: This is a message at time ' . $curDate . "\n\n";
        $counter = rand(1, 10);
    }

    // ob_end_flush();
    // flush();
    sleep(1);
}
